/**
 * 
 */
package com.feib.stms.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.feib.stms.model.MenuItem;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.MenuItemService;

/**
 * @title (#)Stms9004ActionBean.java<br>
 * @description 系統功能設定 <br>
 * @author Lion Gao<br>
 * @version 1.0.0 2012/05/23
 * @copyright Far Eastern International Bank Copyright (c) 2012<br>
 * @2012/05/23 create by Lion Gao<br>
 *
 */
public class Stms9004ActionBean extends BaseActionBean 
{
	private static final long serialVersionUID = -3360927795653829350L;
	
    private static final String DEFAULT_JSP = "/WEB-INF/views/stms9004/stms9004.jsp";
    private static final String DETAIL_JSP = "/WEB-INF/views/stms9004/stms9004Detail.jsp";
    private static final String CREATE_JSP = "/WEB-INF/views/stms9004/stms9004Create.jsp";
    
    /*畫面sortHeader傳回來的值*/
	private static List<String> SORT_KEYS = new ArrayList<String>();
	static{
		SORT_KEYS.add("parentMenuItem".toLowerCase());
		SORT_KEYS.add("menuNo".toLowerCase());
		SORT_KEYS.add("actionName".toLowerCase());
	}

	/*使用SORT_KEYS作key值取得對應的資料庫欄位名稱*/
	private static Map<String,String> SORT_FIELDS =  new HashMap<String, String>();
	static{
		SORT_FIELDS.put("parentMenuItem".toLowerCase(), "PARENT_MENU_ITEM_PK");
		SORT_FIELDS.put("menuNo".toLowerCase(), "MENU_NO");
		SORT_FIELDS.put("actionName".toLowerCase(), "ACTION_NAME");
	}
    
    /** 
     * 查詢條件-程式類別
     */
    private String qryMenuTypeIdForm;
    
    /**
     * 查詢條件-程式代號
     */
    private String qryMenuIdForm;

    /**
     * 查詢條件-程式名稱
     */
    private String qryActionNameForm;
    
    /**
     * 查詢結果(多筆)
     */
    private PaginatedList<MenuItem> queryResult;
    
    /**
     * 新增綁定MenuItem
     */
    private MenuItem createMenuItem;
    
    /**
     * 更新/刪除-綁定MenuItem
     */
    private MenuItem viewMenuItem;
    
    /**
     * 上層程式-下拉選單
     */
    private List<MenuItem> menuItems;
    
    /**
     * 更新/刪除-綁定查詢條件
     */
    @Validate( required=true, on={"doViewDetail"})
    private Long qryMenuItemPk;
   
    @SpringBean("menuItemService")
    private MenuItemService menuItemService;
    
    /**
     * 執行結果信息
     */
    private String message;
    
    /**
     * 標記新增或修改
     */
    private String operation;
   
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 查詢
     * @return
     */
    public Resolution doQuery()
    {
        logger.debug("Enter doQuery mehtod.");
        logger.debug("qryMenuTypeIdForm={}, qryMenuIdForm={}, qryActionNameForm={} ", new Object[]{qryMenuTypeIdForm, qryMenuIdForm, qryActionNameForm });
        
        /* 設定換頁、排序等條件*/
        String sortCriterion = "parentMenuItem";
		int sortDirection = 2; 
		PaginatedList<MenuItem> qryCondition = new PaginatedList<MenuItem>();
        if (null != queryResult)
        {	
        	//畫面傳入的排序字段
            sortCriterion = queryResult.getSortCriterion();
            sortDirection = queryResult.getSortDirection();
            logger.debug(" sortCriterion={}  sortDirection={} ", new Object[]{queryResult.getSortCriterion(), queryResult.getSortDirection()});
        	qryCondition.setPageNumber(queryResult.getPageNumber());
            qryCondition.setPageSize(queryResult.getPageSize());
            //將畫面傳入的排序字段轉換為資料庫對應的字段
            String dbOrderName = SORT_FIELDS.get(sortCriterion.toLowerCase());
            //設置排序
            qryCondition.setSortCriterion(dbOrderName);      
            qryCondition.setSortDirection(sortDirection);
        }
        /*沒有設定排序則默認以第一欄作排序條件*/
        if (null == queryResult || StringUtils.isEmpty(queryResult.getSortCriterion()) || !SORT_KEYS.contains(queryResult.getSortCriterion().toLowerCase()))
        {
        	qryCondition.setSortCriterion(SORT_FIELDS.get(SORT_KEYS.get(0)));
        }
        //封裝查詢條件
        MenuItem menuItem = new MenuItem();
        menuItem.setMenuNo(qryMenuIdForm);
        menuItem.setActionName(qryActionNameForm);
        //調用service,到資料庫撈取DB
        queryResult = menuItemService.findForPaginatedListByMenuItem(menuItem, qryMenuTypeIdForm, qryCondition); 
        
        if (null == this.queryResult)
        	this.queryResult = qryCondition;
        
        queryResult.setSortCriterion(sortCriterion);
		queryResult.setSortDirection(sortDirection);
        
        //result
        if (CollectionUtils.isEmpty(this.queryResult.getPaginatedList()))
        	this.message = "查無資料！";
        
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 跳轉新增畫面
     * @return
     */
    public Resolution doCreate()
    {	
    	logger.debug("Enter doInitCreate mehtod.");
    	this.operation = "create";
    	//將畫面下拉選單上層程式列表查詢出來
    	menuItems = menuItemService.initMenuItemOptionList();
    	return new ForwardResolution(CREATE_JSP); 
    }
    
    /**
     * 確認
     * @return
     */
    public Resolution doSave()
    {	
    	logger.debug("Enter doSave mehtod.");
    	if(this.operation != null && this.operation.equals("create")){
    		createMenuItem.setCreatedDate(new Date());
        	createMenuItem.setUpdatedDate(new Date());
        	
        	int insertCount = menuItemService.saveMenuItem(createMenuItem);
        	
        	message = insertCount > 0?"新增成功！":"新增失敗!";
        	if(insertCount > 0){//新增成功，則跳轉到查詢畫面
        		return doQuery();
        	}
        	return new ForwardResolution(CREATE_JSP); 
    	}else if(this.operation != null && this.operation.equals("update")){
    		int insertCount = menuItemService.updateMenuItem(viewMenuItem);
            
        	message = insertCount > 0?"修改成功！":"修改失敗!";
        	if(insertCount > 0){//新增成功，則跳轉到查詢畫面
        		return doQuery();
        	}
            return new ForwardResolution(DETAIL_JSP); 
    	}
    	return doQuery();
    }
    
    /**
     * 跳轉更新/刪除畫面
     * @return
     */
    public Resolution doUpdate()
    {
        logger.debug("Enter doViewDetail mehtod.");
        this.operation = "update";
        //將畫面下拉選單上層程式列表查詢出來
    	menuItems = menuItemService.initMenuItemOptionList();
    	//根據pk查詢出該筆資料
        viewMenuItem = menuItemService.getByMenuItemPk(qryMenuItemPk);
        return new ForwardResolution(DETAIL_JSP); 
    }
     
    /**
     * 刪除
     * @return
     */
    public Resolution doDelete()
    {
        logger.debug("Enter doDelete mehtod.");
        int parentCount = menuItemService.countParentMenuItem(viewMenuItem.getMenuItemPk());
        if(parentCount > 0){
        	message = "刪除失敗，該程式下有子程式所引用!";
        	return doQuery();
        }
        //result
        int insertCount = menuItemService.deleteMenuItem(viewMenuItem.getMenuItemPk());
    	message = insertCount > 0?"刪除成功！":"刪除失敗!";
    	if(insertCount > 0){//刪除成功，則跳轉到查詢畫面
    		return doQuery();
    	}
        return new ForwardResolution(DETAIL_JSP); 
    }
    
    /**
     * 取消
     * @return
     */
    public Resolution doCancel()
    {
    	return doQuery();
    }
    
	/**
	 * @return menuItemService
	 */
	public MenuItemService getMenuItemService() {
		return menuItemService;
	}

	/**
	 * @param menuItemService 的設定的 menuItemService
	 */
	public void setMenuItemService(MenuItemService menuItemService) {
		this.menuItemService = menuItemService;
	}

	/**
	 * @return message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message 的設定的 message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return qryActionNameForm
	 */
	public String getQryActionNameForm() {
		return qryActionNameForm;
	}

	/**
	 * @param qryActionNameForm 的設定的 qryActionNameForm
	 */
	public void setQryActionNameForm(String qryActionNameForm) {
		this.qryActionNameForm = qryActionNameForm;
	}
	
	/**
	 * @return qryMenuIdForm
	 */
	public String getQryMenuIdForm() {
		return qryMenuIdForm;
	}

	/**
	 * @param qryMenuIdForm 的設定的 qryMenuIdForm
	 */
	public void setQryMenuIdForm(String qryMenuIdForm) {
		this.qryMenuIdForm = qryMenuIdForm;
	}

	/**
	 * @return qryMenuTypeIdForm
	 */
	public String getQryMenuTypeIdForm() {
		return qryMenuTypeIdForm;
	}

	/**
	 * @param qryMenuTypeIdForm 的設定的 qryMenuTypeIdForm
	 */
	public void setQryMenuTypeIdForm(String qryMenuTypeIdForm) {
		this.qryMenuTypeIdForm = qryMenuTypeIdForm;
	}

	/**
	 * @return queryResult
	 */
	public PaginatedList<MenuItem> getQueryResult() {
		return queryResult;
	}

	/**
	 * @param queryResult 的設定的 queryResult
	 */
	public void setQueryResult(PaginatedList<MenuItem> queryResult) {
		this.queryResult = queryResult;
	}

	/**
	 * @return createMenuItem
	 */
	public MenuItem getCreateMenuItem() {
		return createMenuItem;
	}

	/**
	 * @param createMenuItem 的設定的 createMenuItem
	 */
	public void setCreateMenuItem(MenuItem createMenuItem) {
		this.createMenuItem = createMenuItem;
	}

	/**
	 * @return menuItems
	 */
	public List<MenuItem> getMenuItems() {
		return menuItems;
	}

	/**
	 * @param menuItems 的設定的 menuItems
	 */
	public void setMenuItems(List<MenuItem> menuItems) {
		this.menuItems = menuItems;
	}

	/**
	 * @return viewMenuItem
	 */
	public MenuItem getViewMenuItem() {
		return viewMenuItem;
	}

	/**
	 * @param viewMenuItem 的設定的 viewMenuItem
	 */
	public void setViewMenuItem(MenuItem viewMenuItem) {
		this.viewMenuItem = viewMenuItem;
	}

	/**
	 * @return qryMenuItemPk
	 */
	public Long getQryMenuItemPk() {
		return qryMenuItemPk;
	}

	/**
	 * @param qryMenuItemPk 的設定的 qryMenuItemPk
	 */
	public void setQryMenuItemPk(Long qryMenuItemPk) {
		this.qryMenuItemPk = qryMenuItemPk;
	}

	/**
	 * @return operation
	 */
	public String getOperation() {
		return operation;
	}

	/**
	 * @param operation 的設定的 operation
	 */
	public void setOperation(String operation) {
		this.operation = operation;
	}
	
}
